//
//  CXTabBarController.m
//  Lottery
//
//  Created by 黄修勇 on 12-4-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CXTabBarController.h"
#import <QuartzCore/QuartzCore.h>

@interface CXTabBarController ()

-(void)setDefault;//设置默认 的参数
-(void)reloadTabBarImageViewsByViewControllers:(NSArray *)array;//更新item上的image数量
-(void)setIsSelect:(BOOL)isSelect index:(NSInteger)index;
@end

@implementation CXTabBarController

@synthesize itemSelectModel=_itemSelectModel;

@synthesize tabBarBackgroundView=_tabBarBackgroundView;
@synthesize tabItemNormalImages=_tabItemNormalImages;
@synthesize tabItemSelectImages=_tabItemSelectImages;

@synthesize tabItemSelectAnimated=_tabItemSelectAnimated;

@synthesize selectItemBackgroundView=_selectItemBackgroundView;

-(void)dealloc{
    
    [_tabBarBackgroundView release];
    [_tabItemNormalImages release];
    [_tabItemSelectImages release];
    [_selectItemBackgroundView release];
    [tabBarView release];
    [super dealloc];
}


-(void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated{
    
    if ([viewControllers isEqualToArray:self.viewControllers]) {
        return;
    }
    
    [self reloadTabBarImageViewsByViewControllers:viewControllers];
    
    [super setViewControllers:viewControllers animated:animated];
    
    [self.tabBar bringSubviewToFront:tabBarView];
}

-(void)setSelectedIndex:(NSUInteger)selectedIndex{
    
    if (self.selectedIndex==selectedIndex) {
        return;
    }
    if (_itemSelectModel==CXTabBarControllerSelectModelSingle) {
        [tabBarView setSelectIndex:selectedIndex animated:self.tabItemSelectAnimated];
    }else {
        [self setIsSelect:NO index:self.selectedIndex];
        [self setIsSelect:YES index:selectedIndex];
    }
    [super setSelectedIndex:selectedIndex];
    
    [self.tabBar bringSubviewToFront:tabBarView];
    
}

-(void)setSelectedViewController:(UIViewController *)selectedViewController{
    
    if ([selectedViewController isEqual:self.selectedViewController]) {
        return;
    }
    
    NSInteger selectIndex=0;
    for (int i=0; i<self.viewControllers.count; i++) {
        if ([[self.viewControllers objectAtIndex:i] isEqual:selectedViewController]) {
            selectIndex=i;
            break;
        }
    }
    if (selectIndex>5) {
        selectIndex=5;
    }
    
    if (_itemSelectModel==CXTabBarControllerSelectModelSingle) {
        [tabBarView setSelectIndex:selectIndex animated:self.tabItemSelectAnimated];
    }else {
        [self setIsSelect:NO index:self.selectedIndex];
        [self setIsSelect:YES index:selectIndex];
    }
    [super setSelectedViewController:selectedViewController];
    [self.tabBar bringSubviewToFront:tabBarView];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setDefault];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

////

-(void)setItemSelectModel:(CXTabBarControllerSelectModel)itemSelectModel{
    
    if (itemSelectModel==_itemSelectModel) {
        return;
    }
    _itemSelectModel=itemSelectModel;
    
    NSInteger selectIndex=self.selectedIndex;
    UIImageView *imgView=nil;
    if (selectIndex>=0&&[tabBarView.imageViewArray count]>0) {
        imgView=[(CXTabBarItemView *)[tabBarView.imageViewArray objectAtIndex:selectIndex] backgroundImageView];
    }
    if (_itemSelectModel==CXTabBarControllerSelectModelSingle) {
        tabBarView.selectItemView.hidden=NO;
        if (_tabItemNormalImages.count>selectIndex) {
            imgView.image=[_tabItemNormalImages objectAtIndex:selectIndex];
        }else {
            imgView.image=nil;
        }
        [tabBarView setSelectIndex:selectIndex animated:self.tabItemSelectAnimated];
        
    }else if (_itemSelectModel==CXTabBarControllerSelectModelNumbers) {
        tabBarView.selectItemView.hidden=YES;
        if (_tabItemSelectImages.count>selectIndex) {
            imgView.image=[_tabItemSelectImages objectAtIndex:selectIndex];
        }else {
            imgView.image=nil;
        }
    }
}

-(void)setTabBarBackgroundView:(UIView *)tabBarBackgroundView{
    
    if ([tabBarBackgroundView isEqual:_tabBarBackgroundView]) {
        return;
    }
    [_tabBarBackgroundView release];
    [_tabBarBackgroundView removeFromSuperview];
    _tabBarBackgroundView=[tabBarBackgroundView retain];
    _tabBarBackgroundView.frame=CGRectMake(0.0f, 0.0f, tabBarView.frame.size.width, tabBarView.frame.size.height);
    _tabBarBackgroundView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _tabBarBackgroundView.userInteractionEnabled=NO;
    [tabBarView insertSubview:_tabBarBackgroundView atIndex:0];
}

-(void)setTabItemNormalImages:(NSArray *)tabItemNormalImages{
    
    [self setTabItemNormalImages:tabItemNormalImages animated:NO];
}

-(void)setTabItemNormalImages:(NSArray *)tabItemNormalImages animated:(BOOL)animated{
    
    if ([tabItemNormalImages isEqualToArray:_tabItemNormalImages]) {
        return;
    }
    
    [_tabItemNormalImages release];
    _tabItemNormalImages=[tabItemNormalImages retain];
    
    for (int i=0; i<tabBarView.imageViewArray.count; i++) {
        UIImageView *imgView=[(CXTabBarItemView *)[tabBarView.imageViewArray objectAtIndex:i] imageView];
        if (animated) {
            CATransition *transition = [CATransition animation];  
            transition.duration = 0.5f;           
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
            transition.removedOnCompletion = YES;  
            transition.fillMode = kCAFillModeBackwards;  
            [imgView.layer addAnimation:transition forKey:nil]; 
        }
        if (self.selectedIndex==i&&_itemSelectModel==CXTabBarControllerSelectModelNumbers) {
            if (_tabItemSelectImages.count!=0) {
                imgView.image=[_tabItemSelectImages objectAtIndex:i];
                continue;
            }
        } 
        
        if (i<_tabItemNormalImages.count) {
            imgView.image=[_tabItemNormalImages objectAtIndex:i];
        }else {
            imgView.image=nil;
        }
    }
}

-(void)setTabItemSelectImages:(NSArray *)tabItemSelectImages{
    
    if ([tabItemSelectImages isEqualToArray:_tabItemSelectImages]) {
        return;
    }
    [_tabItemSelectImages release];
    _tabItemSelectImages=[tabItemSelectImages retain];
    
    NSInteger selectIndex=self.selectedIndex;
    if (selectIndex>=0&&_itemSelectModel==CXTabBarControllerSelectModelNumbers) {
        
        UIImageView *imgView=[(CXTabBarItemView *)[tabBarView.imageViewArray objectAtIndex:selectIndex] backgroundImageView];
        imgView.image=[_tabItemSelectImages objectAtIndex:self.selectedIndex];
    }
}

-(void)setSelectItemBackgroundView:(UIView *)selectItemBackgroundView{
    
    [tabBarView setSelectItemView:selectItemBackgroundView];
}

-(UIView *)selectItemBackgroundView{
    
    return [tabBarView selectItemView];
}

-(void)setDefault{
    
    tabBarView=[[CXTabBarBackGroundView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, self.tabBar.frame.size.width, self.tabBar.frame.size.height)];
    tabBarView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.tabBar addSubview:tabBarView];
    
    UIView *tempView=[[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f)];
    self.tabBarBackgroundView=tempView;
    [tempView release];
    
    self.tabItemSelectAnimated=YES;
    self.itemSelectModel=CXTabBarControllerSelectModelSingle;
    
}


-(void)reloadTabBarImageViewsByViewControllers:(NSArray *)array{
    
    NSInteger maxNum=0;
    
    if (array.count>=5) {
        maxNum=MaxTabImageViewNumber;
    }else {
        maxNum=array.count;
    }
    
    BOOL imageViewNumberIsChange=YES;
    
    float tempWeidth=tabBarView.frame.size.width/maxNum;
    float tempHeight=tabBarView.frame.size.height;
    
    if (maxNum>tabBarView.imageViewArray.count) {
        
        for (int i=tabBarView.imageViewArray.count; i<maxNum; i++) {
            CXTabBarItemView *tempImageView=[[CXTabBarItemView alloc]initWithFrame:CGRectMake(i*tempWeidth, 0.0f, tempWeidth, tempHeight)];
            tempImageView.userInteractionEnabled=NO;
            [tabBarView.imageViewArray addObject:tempImageView];
            if (i<_tabItemNormalImages.count) {
                tempImageView.imageView.image=[_tabItemNormalImages objectAtIndex:i];
            }
            [tabBarView addSubview:tempImageView];
            [tempImageView release];
        }
    }else if(maxNum<tabBarView.imageViewArray.count){
        NSRange rang=NSMakeRange(maxNum, tabBarView.imageViewArray.count-maxNum);
        NSArray *tempRemoveArray=[tabBarView.imageViewArray subarrayWithRange:rang];
        for (UIView *tempView in tempRemoveArray) {
            [tempView removeFromSuperview];
        }
        [tabBarView.imageViewArray removeObjectsInRange:rang];
    }else {
        imageViewNumberIsChange=NO;
    }
    
    if (imageViewNumberIsChange) {
        [tabBarView layoutSubviews];
    }
    for (int i=0; i<[array count]; i++) {
        CXTabBarItemView *item=[tabBarView.imageViewArray objectAtIndex:i];
        item.titleLabel.text=[[array objectAtIndex:i] title];
    }
    
    if (array.count==0) {
        self.selectItemBackgroundView.hidden=YES;
    }else {
        self.selectItemBackgroundView.frame=CGRectMake(tabBarView.selectIndex*(tabBarView.frame.size.width/array.count), 0.0f, tempWeidth, tempHeight);
        self.selectItemBackgroundView.hidden=NO;
    }
}

-(void)setIsSelect:(BOOL)isSelect index:(NSInteger)index{
    
    UIImageView *imgView=[(CXTabBarItemView *)[tabBarView.imageViewArray objectAtIndex:index] backgroundImageView];
    if (self.tabItemSelectAnimated==YES) {
        CATransition *transition = [CATransition animation];  
        transition.duration = 0.5f;           
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; 
        transition.removedOnCompletion = YES;  
        transition.fillMode = kCAFillModeBackwards;  
        [imgView.layer addAnimation:transition forKey:nil];
    }
    UIImage *img=nil;
    if (isSelect) {
        if (_tabItemSelectImages.count>index) {
            img=[_tabItemSelectImages objectAtIndex:index];
        }else {
            img=nil;
        }
    }else {
        if (_tabItemNormalImages.count>index) {
            img=[_tabItemNormalImages objectAtIndex:index];
        }else {
            img=nil;
        }
    }
    imgView.image=img;
}


-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    
    return YES;
}
@end

@implementation CXTabBarBackGroundView

@synthesize imageViewArray=_imageViewArray;
@synthesize selectItemView=_selectItemView;
@synthesize selectIndex=_selectIndex;

-(void)dealloc{
    
    [_imageViewArray release];
    [super dealloc];
}

-(id)initWithFrame:(CGRect)frame{
    
    self=[super initWithFrame:frame];
    if (self) {
        _imageViewArray=[NSMutableArray new];
        self.userInteractionEnabled=NO;
    }
    return self;
}

-(void)setSelectItemView:(UIView *)selectItemView{
    
    if ([selectItemView isEqual:_selectItemView]) {
        return;
    }
    [_selectItemView removeFromSuperview];
    [_selectItemView release];
    
    _selectItemView=[selectItemView retain];
    _selectIndex=0;
    CGRect rect;
    if (_imageViewArray.count==0) {
        rect=CGRectMake(0.0f, 0.0f, 0.0f, 0.0f);
    }else {
        rect=CGRectMake(_selectIndex*(self.frame.size.width/_imageViewArray.count), 0.0f, self.frame.size.width/_imageViewArray.count, self.frame.size.height);
    }
    
    _selectItemView.frame=rect;
    _selectItemView.userInteractionEnabled=NO;
    [self insertSubview:_selectItemView atIndex:1];
}

-(void)layoutSubviews{
    
    float imageWeidth=self.frame.size.width/_imageViewArray.count;
    float imageHeight=self.frame.size.height;
    _selectItemView.frame=CGRectMake(_selectIndex*imageWeidth, 0.0f, imageWeidth, imageHeight);
    for (int i=0; i<[_imageViewArray count]; i++) {
        UIView *view=[_imageViewArray objectAtIndex:i];
        view.frame=CGRectMake(imageWeidth*i, 0.0f, imageWeidth, imageHeight);
    }
}

-(void)setSelectIndex:(NSInteger)selectIndex{
    
    [self setSelectIndex:selectIndex animated:NO];
    
}

-(void)setSelectIndex:(NSInteger)selectIndex animated:(BOOL)animated{
    
    if (_selectIndex==selectIndex)
    {
        return;
    }
    _selectIndex=selectIndex;
    
    CGRect rect=CGRectMake(_selectItemView.frame.size.width*selectIndex, _selectItemView.frame.origin.y, _selectItemView.frame.size.width, _selectItemView.frame.size.height);
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        [_selectItemView setFrame:rect];
        [UIView commitAnimations];
    }else {
        [_selectItemView setFrame:rect];
    }
}
@end

@implementation CXTabBarItemView

@synthesize imageView=_imageView;
@synthesize backgroundImageView=_backgroundImageView;
@synthesize titleLabel=_titleLabel;

-(void)dealloc{
    
    [_imageView release];
    [_backgroundImageView release];
    [_titleLabel release];
    [super dealloc];
}

-(id)initWithFrame:(CGRect)frame{
    
    self=[super initWithFrame:frame];
    if (self) {
        _backgroundImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height)];
        _backgroundImageView.backgroundColor=[UIColor clearColor];
        //_backgroundImageView.image = [UIImage imageNamed:@"TabBarBkg.png"];
        _backgroundImageView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        //self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"TabBarBkg.png"]];
        [self addSubview:_backgroundImageView];
        
        _imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height)];
        _imageView.contentMode=UIViewContentModeScaleAspectFit;
        [self addSubview:_imageView];
        _imageView.autoresizingMask=UIViewAutoresizingFlexibleWidth;
        
        _titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0.0f, frame.size.height-15.0f-2.0f, frame.size.width, 15.0f)];
        _titleLabel.backgroundColor=[UIColor clearColor];
        _titleLabel.textAlignment=UITextAlignmentCenter;
        _titleLabel.textColor=[UIColor whiteColor];
        _titleLabel.font=[UIFont boldSystemFontOfSize:11.0f];
        _titleLabel.autoresizingMask=UIViewAutoresizingFlexibleWidth;
        //[self addSubview:_titleLabel];
        self.userInteractionEnabled=NO;
    }
    return self;
}

@end
